/*
 * Copyright 2024 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.permission.api;

import com.lap.framework.context.helper.UserHelper;
import com.lap.framework.validator.Update;
import com.lap.framework.watchdog.annotation.Repeat;
import com.lap.permission.domain.entity.Header;
import com.lap.permission.dto.request.HeaderRequest;
import com.lap.permission.service.HeaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <pre>
 *  列表头 Controller,控制业务流程。
 *  提供包括业务流程校验,业务流程控制。当流程非常复杂时候,请在API和Service之间添加一层Manager。
 *  Controller 对外开放Rest,同时可以做简单流程控制。Manager复杂流程控制。Service数据完整性(事务)。DAO/Mapper持久操作。
 *  流程简单: Controller->Service->DAO
 *  复杂流程: Controller->Manager->Service->DAO
 *  对外流程: Controller->Manager->Service->DAO
 * 					    |->外部服务
 *  <b>uri 规则</b>
 *   uri 名词复数.
 *   列表或分页 : GET /persons
 *   单人信息   : GET /persons/1
 *   新增      : POST /persons
 *   修改      : PUT /persons
 *   删除      : DELETE /persons/1
 * </pre>
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 * @see HeaderService
 * @see HeaderRequest
 * @see Header
 */
@Tag(name = "列表头")
@RequiredArgsConstructor
@RestController
@RequestMapping("api/headers")
public class HeaderController {

    private final HeaderService headerService;

    @Operation(summary = "根据编码获取列表头")
    @GetMapping
    public List<String> queryByCode(@RequestParam String code) {
        Header header = headerService.queryByUserIdAndCode(UserHelper.getUserId(), code);
        if (Objects.nonNull(header))
            return Arrays.asList(header.getContent().split(","));

        return Collections.emptyList();
    }

    @Operation(summary = "列表头保存")
    @Repeat
    @PutMapping
    public Header saveHeader(@RequestBody @Validated(Update.class) HeaderRequest request) {
        Header query = headerService.queryByUserIdAndCode(UserHelper.getUserId(), request.getCode());

        String content = String.join(",", request.getContent());
        if (Objects.isNull(query)) {
            Header header = new Header();
            header.setUserId(UserHelper.getUserId());
            header.setCode(request.getCode());
            header.setContent(content);
            headerService.insertHeader(header);
        } else {
            query.setContent(content);
            headerService.updateHeader(query);
        }
        return query;
    }

}
